import { defineStore } from 'pinia'
import { useStorage } from '@/hooks/web/useStorage'
import { loginApi, mobileLoginApi, authInfoApi } from '@/api/login'
import { UserLoginType, MobileLoginType, UserType } from '@/api/login/types'
import config from '@/config/axios/config'
import router, { resetRouter } from '@/router'

const { getStorage, setStorage } = useStorage()

const TOKEN_KEY = 'Authorization'
const USER_INFO_KEY = 'UserInfo'

interface UserState {
  token: string
  userInfo: Nullable<UserType>
}

export const useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      token: getStorage(TOKEN_KEY),
      userInfo: getStorage(USER_INFO_KEY)
    }
  },
  getters: {
    apiToken(): string {
      return this.token
    }
  },
  actions: {
    setToken(token: string) {
      this.token = token
      setStorage(TOKEN_KEY, token)
    },
    async login(data: UserLoginType) {
      const res = await loginApi(data)
      if (res.code === config.code) {
        this.setToken(res.data)
        const info = await this.getUserInfo(res.data)
        return info
      }
    },
    async mobileLogin(data: MobileLoginType) {
      const res = await mobileLoginApi(data)
      if (res.code === config.code) {
        this.setToken(res.data)
        const info = await this.getUserInfo(res.data)
        return info
      }
    },
    async getUserInfo(data: string) {
      const res = await authInfoApi(data)
      if (res.code === config.code) {
        setStorage(USER_INFO_KEY, res.data)
        this.userInfo = res.data
      }
      return res
    },
    tokenError() {
      const { clear } = useStorage()
      clear()
      resetRouter() // 重置静态路由表
      router.replace('/login')
    }
  }
})
